package com.l024.hi_device_util.applist;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/6/1 21:12
 * @Notes 抓取app列表
 */
public class AppListUtil {

    public List<PackageInfo> getAppInfos(Context context){
        List<PackageInfo> packages = new ArrayList<PackageInfo>();
        try {
            List<PackageInfo> packageInfos = context.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES |
                    PackageManager.GET_SERVICES);
            for (PackageInfo info : packageInfos) {
                if(!isSystemApp(info)){
                    packages.add(info);
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();;
        }
        return packages;
    }

    // 通过packName得到PackageInfo，作为参数传入即可
    private boolean isSystemApp(PackageInfo pi) {
        boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
        boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
        return isSysApp || isSysUpd;
    }
} 